﻿using CloudMusic.Helper;
using CloudMusic.Model;
using CloudMusic.ViewModel;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Web.Script.Serialization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Navigation;

namespace CloudMusic.UC
{
    /// <summary>
    /// UCLogin.xaml 的交互逻辑
    /// </summary>
    public partial class UCLogin
    {

        private string strPhone;
        private string password;
        private string verification;
        private string strEmail;
        private bool flag = true;
        /// <summary>
        /// 登录委托
        /// </summary>
        public event EventHandler loginEvent;
        public static event EventHandler loginRecEvent;
        /// <summary>
        /// 
        /// </summary>
        private DataServiceHelper ds = new DataServiceHelper();
        /// <summary>
        /// 用户信息
        /// </summary>
        List<userInfo> us = new List<userInfo>();
        /// <summary>
        /// 喜欢的歌曲ids
        /// </summary>
        List<LikesIdModel> likeIds = new List<LikesIdModel>();
        public UCLogin()
        {
            InitializeComponent();
        }

        private void countryCode_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            phonePop.IsOpen = true;
        }
        private void login_MouseDown(object sender, MouseButtonEventArgs e)
        {
            login.Focus();
        }
        /// <summary>
        /// 邮箱登录-网易邮箱
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void emailBtn_Click(object sender, RoutedEventArgs e)
        {
            if (loignUserPhone.Text != "")
            {
                if (RegexHelper.IsValidEmail(email.Text.Trim()))
                {
                    strEmail = email.Text.Trim();
                    password = emailPassword.Password.Trim();
                    SetUserInfo("email");
                    if (flag == false)
                    {
                        eamilErr.Visibility = Visibility.Visible;
                        emailErrText.Text = "用户名或者密码错误";
                    }
                }
                else
                {
                    eamilErr.Visibility = Visibility.Visible;
                    emailErrText.Text = "请输入正确的邮箱";
                }
            }
            else
            {
                eamilErr.Visibility = Visibility.Visible;
                emailErrText.Text = "请输入邮箱";
            }
        }
        /// <summary>
        /// 手机号/密码的登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void loginBtn_Click(object sender, RoutedEventArgs e)
        {
            if (loignUserPhone.Text != "")
            {
                if (RegexHelper.IsCellphoneNum(loignUserPhone.Text.Trim()))
                {
                    strPhone = loignUserPhone.Text.Trim();
                    password = loginUserPassword.Password.Trim();
                    SetUserInfo("login");
                    if (flag == false)
                    {
                        loginErr.Visibility = Visibility.Visible;
                        loginErrText.Text = "用户名或者密码错误";
                    }
                }
                else
                {
                    loginErr.Visibility = Visibility.Visible;
                    loginErrText.Text = "请输入11位数字手机号";
                }
            }
            else
            {
                loginErr.Visibility = Visibility.Visible;
                loginErrText.Text = "请输入手机号";
            }

            //loginErrText
        }
        /// <summary>
        /// 跳转到web
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            if (e.Uri != null && string.IsNullOrEmpty(e.Uri.OriginalString) == false)
            {
                string uri = e.Uri.AbsoluteUri;
                Process.Start(new ProcessStartInfo(uri));
            }
            else
            {
                Process.Start(new ProcessStartInfo("https://music.163.com/#/download"));
            }
            e.Handled = true;
        }
        /// <summary>
        /// 跳转到注册
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rigest_Click(object sender, RoutedEventArgs e)
        {
            if (policyCheckBox.IsChecked == true)
            {
                loginPanle.Visibility = Visibility.Collapsed;
                registerPanle.Visibility = Visibility.Visible;
            }
            else
            {
                MessageBox.Show("勾选");
            }

        }
        /// <summary>
        /// 返回登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void back_Click(object sender, RoutedEventArgs e)
        {
            registerPanle.Visibility = Visibility.Collapsed;
            emailPanle.Visibility = Visibility.Collapsed;
            loginPanle.Visibility = Visibility.Visible;

        }
        /// <summary>
        /// 校验码页面下一步
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void netxCode_Click(object sender, RoutedEventArgs e)
        {
            verification = Verification.Text.Trim();
            Regex regex = new Regex("^\\d[0-9]{4}$");
            if (regex.IsMatch(verification))
            {
                var check = CommonHelper.Get("http://localhost:3000/captcha/verify?phone=" + strPhone + "&captcha=" + verification + "");
                JObject jo = (JObject)JsonConvert.DeserializeObject(check);
                if (jo["code"].ToString() == "200")
                {
                    SetUserInfo("regist");
                }
                else
                {
                    MessageBox.Show(jo["message"].ToString());
                }
            }
        }
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void registBtn_Click(object sender, RoutedEventArgs e)
        {
            if (RegexHelper.IsValidTel(registerUserPhone.Text.Trim().ToString()))
            {
                strPhone = registerUserPhone.Text.Trim();
                password = registerPassword.Password.Trim();
                registerPanle.Visibility = Visibility.Collapsed;
                yzPanle.Visibility = Visibility.Visible;
                recapture_Click(sender, e);
            }
            else
            {
                registErr.Visibility = Visibility.Visible;
            }
        }
        /// <summary>
        /// 校验页面返回登陆
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void back_yz_Click(object sender, RoutedEventArgs e)
        {
            yzPanle.Visibility = Visibility.Collapsed;
            loginPanle.Visibility = Visibility.Visible;
        }
        /// <summary>
        /// 其他登录方式按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void next_Click(object sender, RoutedEventArgs e)
        {
            codeLogin.Visibility = Visibility.Collapsed;
            loginPanle.Visibility = Visibility.Visible;
        }
        /// <summary>
        /// 登录界面点击二维码跳转到二维码登录界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void code_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            loginPanle.Visibility = Visibility.Collapsed;
            codeLogin.Visibility = Visibility.Visible;
        }
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void recapture_Click(object sender, RoutedEventArgs e)
        {
            var res = CommonHelper.Get("http://localhost:3000/cellphone/existence/check?phone=" + strPhone);
            JObject check = (JObject)JsonConvert.DeserializeObject(res);
            //var oo = JsonConvert.DeserializeObject<dynamic>(res);
            //string df = oo.exist;
            if (check["exist"].ToString() == "1") { MyCustomControlLibrary.MMessageBox.ShowAlert("该账号已存在！", Orientation.Horizontal, null, "#3ca9fe", false); return; };
            var code = CommonHelper.Get("http://localhost:3000/captcha/sent?phone=" + strPhone);
            JObject jo = (JObject)JsonConvert.DeserializeObject(code);
            if (jo["code"].ToString() == "200")
            {
                recapture.Background = new SolidColorBrush(Color.FromArgb(255, 222, 222, 222));
                recapture.IsEnabled = false;
                recapture.Foreground = new SolidColorBrush(Colors.Gray);
                for (int i = 60 - 1; i >= 0; i--)
                {
                    if (i < 10) recapture.Content = $"00:0{i}";
                    else recapture.Content = $"00:{i}";
                    await Task.Delay(TimeSpan.FromSeconds(1));
                }
                recapture.IsEnabled = true;
                recapture.Background = new SolidColorBrush(Colors.Red);
                recapture.Foreground = new SolidColorBrush(Colors.White);
                recapture.Content = "重新获取";
            }
        }
        /// <summary>
        /// 点击登录界面网易邮箱按钮登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void wyBtn_login_Click(object sender, RoutedEventArgs e)
        {
            loginPanle.Visibility = Visibility.Collapsed;
            registerPanle.Visibility = Visibility.Collapsed;
            emailPanle.Visibility = Visibility.Visible;
            emailBtn.Content = "登 录";
        }
        /// <summary>
        /// 点击注册页面网易邮箱按钮注册
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void wyiBtn_regist_Click(object sender, RoutedEventArgs e)
        {
            loginPanle.Visibility = Visibility.Collapsed;
            registerPanle.Visibility = Visibility.Collapsed;
            emailPanle.Visibility = Visibility.Visible;
            emailBtn.Content = "注 册";
        }
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="loginType"></param>
        private void SetUserInfo(string loginType)
        {
            var list = "";
            JObject obj = new JObject();
            var profile = "";
            password = HttpUtility.UrlEncode(password);
            userInfo userInfo = null;
            switch (loginType)
            {
                case "login":
                    list = CommonHelper.Get("http://localhost:3000/login/cellphone?phone=" + strPhone + "&password=" + password + "");
                    break;
                case "regist":
                    list = CommonHelper.Get("http://localhost:3000/register/cellphone?phone=" + strPhone + "&password=" + password + "&captcha=" + verification + "");
                    break;
                case "eamile":
                    list = CommonHelper.Get("http://localhost:3000/login?email=" + strEmail + "&password=" + password + "");
                    break;
                default:
                    break;
            }
            if (list.Length > 0)
            {
                var cookie = "";
                obj = (JObject)JsonConvert.DeserializeObject(list);
                if (obj["code"].ToString() == "200")
                {
                    if (list.Contains("cookie"))
                    {
                        cookie = obj["cookie"].ToString();
                    }
                    profile = JsonConvert.SerializeObject(obj["profile"].ToString());
                    JsonReader reader = new JsonTextReader(new StringReader(profile));
                    while (reader.Read())
                    {
                        profile = reader.Value.ToString();
                    }
                    Profile job = JsonConvert.DeserializeObject<Profile>(profile);
                    userInfo = new userInfo
                    {
                        UserId = job.userId,
                        AvatarUrl = job.avatarUrl,
                        Nickname = job.nickname,
                        Signature = job.signature,
                        Gender = job.gender,
                        Birthday = job.birthday,
                        Province = job.province,
                        City = job.city,
                        EventCount = job.eventCount,
                        Followeds = job.followeds,
                        Follows = job.follows,
                        VipType = job.vipType,
                        Cookie = cookie,
                        LonginState = 1,
                        IsChecked = false
                    };
                    PlayListHelper.UserInfos.Add(userInfo);
                    us.Add(userInfo);
                    if (PlayListHelper.UserInfos.Count != 0)
                    {
                        var likes = CommonHelper.GetEquipList<LikesIdModel>(1, "http://localhost:3000/likelist?uid=" + PlayListHelper.UserInfos[0].UserId + "&cookie=" + PlayListHelper.UserInfos[0].Cookie);
                        if (likes.code != 200) return;
                        if (likes.ids.Count != 0)
                        {
                            PlayListHelper.UserLikes.Add(likes);
                            likeIds.Add(likes);
                        }
                    }
                    loginEvent?.Invoke(null, null);
                    loginRecEvent?.Invoke(null, null);
                    if (ckBox.IsChecked == true)
                    {
                        PlayListHelper.UserInfos[0].IsChecked = true;
                        SetFarmCropsInfo();
                    }
                    login.Close();
                }
                else
                {
                    flag = false;
                }
            }

        }

        /// <summary>
        /// 保存登录信息
        /// </summary>
        public void SetFarmCropsInfo()
        {
            try
            {
                ds.SaveUserInfo(us);
                ds.SaveLikesInfo(likeIds);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
        /// <summary>
        /// 验证是否以及注册
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void registerUserPhone_LostFocus(object sender, RoutedEventArgs e)
        {

        }
    }
}
